package com.yunquan.ohana.ui.editProfile

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.yalantis.ucrop.UCrop
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityEditProfileBinding
import com.yunquan.ohana.entity.UserManager
import com.yunquan.ohana.ui.editProfile.dialog.AvatarDialog
import com.yunquan.ohana.ui.editProfile.dialog.NicknameDialog
import com.yunquan.ohana.utils.CameraUtils
import com.yunquan.ohana.utils.FileUtils
import com.yunquan.ohana.utils.L
import com.yunquan.ohana.utils.MediaUtils
import java.io.File

class EditProfileActivity : BaseActivity<ActivityEditProfileBinding, EditProfileViewModel>() {

    private var mCameraResultUri: Uri? = null

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_edit_profile
    }

    override fun initVariableId(): Int {
        return BR.editProfileViewModel
    }

    override fun initParam() {
        super.initParam()
        window.statusBarColor = resources.getColor(R.color.background)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel!!.ui.observe(this) { type ->
            when (type) {
                0 -> {
                    val dialog = AvatarDialog(this)
                    dialog.setOnCheckedListener {
                        if (it == 1) {
                            takePhoto()
                        } else {
                            camera()
                        }
                    }
                    dialog.show()
                }

                1 -> {
                    val dialog = NicknameDialog(this)
                    dialog.setNickname(UserManager.instance.getUser()?.nickname ?: "")
                    dialog.setOnInputListener {
                        showLoading()
                        viewModel!!.updateUserInfo(it, null)
                    }
                    dialog.show()
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun takePhoto() {
        val permissions = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2) {
            arrayOf(
                Manifest.permission.READ_MEDIA_IMAGES,
                Manifest.permission.READ_MEDIA_VIDEO,
                Manifest.permission.READ_MEDIA_AUDIO,
            )
        } else {
            arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        albumPermissionLauncher.launch(permissions)
    }

    @SuppressLint("CheckResult")
    private fun camera() {
        cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            // 裁剪返回
            val resultUri = UCrop.getOutput(data!!)
            resultUri?.path?.let { File(it) }?.let { viewModel!!.uploadAvatar(it) }
        } else if (requestCode == UCrop.RESULT_ERROR) {
            val cropError = UCrop.getError(data!!)
            L.e("裁剪报错->\n${cropError?.message}")
        }
    }

    // 相册选择返回
    private val mAlbumResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        // 这里处理返回结果
        if (result.resultCode == RESULT_OK) {
            result.data?.data?.let { uri ->
                val file = FileUtils.uriToFile(uri)
                val oldFileName = file.name
                val fileName = "CROP_${oldFileName}.jpg"
                val cropFile = File(FileUtils.getFilePath(), fileName)
                UCrop.of(Uri.fromFile(file), Uri.fromFile(cropFile))
                    .withAspectRatio(1f, 1f)
                    .withMaxResultSize(300, 300)
                    .start(this@EditProfileActivity)
            }
        }
    }

    // 拍照并返回数据
    private val mCameraResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        // 这里处理返回结果
        if (result.resultCode == RESULT_OK) {
            val bean = MediaUtils.getImageById(this,mCameraResultUri!!.lastPathSegment!!)
            if (bean != null) {
                val file = File(bean.path!!)
                val oldFileName = file.name
                val fileName = "CROP_${oldFileName}.jpg"
                val cropFile = File(FileUtils.getFilePath(), fileName)
                UCrop.of(Uri.fromFile(file), Uri.fromFile(cropFile))
                    .withAspectRatio(1f, 1f)
                    .withMaxResultSize(300, 300)
                    .start(this@EditProfileActivity)
            }
        }
    }

    private val albumPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
        val granted = result.values.all { it }
        if (granted) {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            mAlbumResult.launch(intent)
        }
    }

    private val cameraPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { state ->
        if (state) {
            val (resultUri, intent) = CameraUtils.takePhoto(this)
            mCameraResultUri = resultUri
            intent?.let { mCameraResult.launch(it) }
        }
    }
}